import { Component, ViewChild, ElementRef, AfterViewInit } from "@angular/core";
import { Store, select } from "@ngrx/store";
import { AppState } from "./store";
import { fromEvent, Observable } from "rxjs";
import { filter, map } from "rxjs/operators";
import { addTodo, delTodo } from "./store/actions/todo.actions";
import { Todo } from "./store/reducers/todo.reducer";
import { selectTodos } from "./store/selector/todo.selectors";
import {
  trigger,
  transition,
  style,
  animate,
  keyframes,
} from "@angular/animations";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
  // 定义动画
  animations: [
    trigger("slide", [
      // 入场动画
      transition(":enter", [
        // 定义void状态的样式
        style({ opacity: 0, transform: "translateY(40px)" }),
        animate(250),
      ]),
      // 出场动画
      // transition(":leave", [
      //   animate(
      //     "600ms 1s ease-out",
      //     style({ opacity: 0, transform: "translateX(100%)" })
      //   ),
      // ]),
      transition(":leave", [
        animate(
          "600ms 1s ease-out",
          keyframes([
            style({ opacity: 0.3, transform: "translateX(-80px)" }),
            style({ opacity: 1, transform: "translateX(100%)" }),
          ])
        ),
      ]),
    ]),
  ],
})
export class AppComponent implements AfterViewInit {
  @ViewChild("AddTodoInput") AddTodoInput!: ElementRef;
  todos: Observable<Todo[]>;
  constructor(private store: Store<AppState>) {
    this.todos = this.store.pipe(select(selectTodos));
  }

  ngAfterViewInit() {
    fromEvent<KeyboardEvent>(this.AddTodoInput.nativeElement, "keyup")
      .pipe(
        filter((event) => event.key === "Enter"),
        map((event) => (<HTMLInputElement>event.target).value),
        map((title) => title.trim()),
        filter((title) => title !== "")
      )
      .subscribe((title) => {
        this.store.dispatch(addTodo({ title }));
        this.AddTodoInput.nativeElement.value = "";
      });
  }

  delTodo(id: string) {
    this.store.dispatch(delTodo({ id }));
  }

  startSlide(event: any) {
    console.log("startSlide");
  }
  doneSlide(event: any) {
    console.log("doneSlide");
  }
}
